<template>
  <view class="goods-detail">
    <customHeader class="goods-detail-title" title="商品详情"></customHeader>
    <view class="scroll-wrap">
      <view class="goods-detail-head">
        <view class="swiper-wrap">
          <swiper
            :duration="500"
            :interval="2000"
            :current="current"
            vertical
            @change="handleSwiperChange"
          >
            <swiper-item
              v-for="(img, index) in detailInfo.goods_detail_img"
              :key="index"
            >
              <image :lazy-load="true" class="head-img" :src="img" />
            </swiper-item> </swiper
          ><view class="extra-info" v-if="swiperInstruct">{{
            swiperInstruct
          }}</view>
        </view>
        <view class="head-main" :class="exChangeOverClass">
          <view class="head-main-title">{{ detailInfo.goods_name }} </view>
          <view class="head-main-extra">
            <view class="spand-flower">
              <view class="flower-num">
                {{ detailInfo.use_petal_num }}
              </view>
              <text>花朵</text>
            </view>
            <view class="surplus" v-if="isShowSurplus">
              仅剩{{ detailInfo.goods_stock }}件
            </view>
            <view v-if="isExchangeOver" class="over">已兑完</view>
            <view class="exchange-num">
              已兑换{{ detailInfo.goods_order_count }}件
            </view>
          </view>
        </view>
      </view>
      <!-- 商品详情 -->
      <view class="goods-introduce">
        <view class="goods-introduce-title">
          商品详情
        </view>
        <view class="goods-introduce-image">
          <rich-text class="rich-text" :nodes="content"></rich-text>
        </view>
      </view>
    </view>
    <!-- 兑换按钮 -->
    <view class="button-wrap">
      <finishButton
        :width="690"
        @click="handleExchangeGoods"
        :disabled="isExchangeOver"
      >
        {{ buttonName }}
      </finishButton>
    </view>

    <at-modal
      class="custom-confirm"
      :is-opened="isShowModal"
      :close-on-click-overlay="false"
      :on-close="handleModalCancel"
      :on-cancel="handleModalCancel"
    >
      <AtModalContent>
        抱歉，您的剩余花朵数不足，先去兑换花朵吧！
      </AtModalContent>
      <AtModalAction>
        <view class="modal-footer" @tap="handleModalOperate">
          <view data-key="cancel">
            我再看看
          </view>
          <view data-key="to-exchange">
            立即前往
          </view>
        </view>
      </AtModalAction>
    </at-modal>
    <!-- toast提示 -->
    <at-toast
      :is-opened="is_opened"
      :text="toastText"
      :on-close="handleCloseToast"
    />
  </view>
</template>
<script>
import Taro from "@tarojs/taro";
import { AtModalAction, AtModalContent } from "taro-ui-vue";
import finishButton from "@/components/finish-button/index";
import { goodsDetail, goodsExchange } from "@/libs/api/exchange-store";
import { handleRichTextStyle } from "@/libs/util";
import customHeader from "@/components/custom-header";
/**兑换类型 */
const EXCHANGE_TYPE = {};
/**实体兑换 */
const Entity_TYPE = 1;
/**公益兑换 */
const Public_Spirited_Type = 2;
/**虚拟兑换 */
const Fictitious_TYPE = 3;

/**兑换花朵不足报错状态码 */
const Not_Flower_Exchange_Code = 4001;
/**库存不足报错状态码 */
const Not_Enough_Stock_Code = 4002;
/**栏目下架错误状态码 */
const CATE_OFF_CODE = 4003;
export default {
  components: {
    finishButton,
    AtModalAction,
    AtModalContent,
    customHeader
  },
  data() {
    return {
      current: 0,
      detailInfo: {},
      goodsId: undefined,
      cate_id: undefined,
      content: "",
      isFromMore: false
    };
  },
  computed: {
    /**已兑完类名 */
    exChangeOverClass() {
      return {
        "exchange-over": this.isExchangeOver
      };
    },
    /**是否显示仅剩的标识 */
    isShowSurplus() {
      const { is_infinite_stock } = this.detailInfo;
      return is_infinite_stock
        ? false
        : this.detailInfo?.is_show_surplus && !this.isExchangeOver;
    },
    /**是否已兑换完 */
    isExchangeOver() {
      return !this.detailInfo?.id || !!this.detailInfo.is_exchanged_over;
    },
    /**提交按钮名 */
    buttonName() {
      return this.isExchangeOver ? "暂无库存" : "立即兑换";
    },
    /**轮播指示 */
    swiperInstruct() {
      const imgTotal = this.detailInfo?.goods_detail_img?.length || 0;
      return imgTotal < 2 ? false : `${this.current + 1}/${imgTotal}`;
    }
  },
  onLoad({ id, cate_id, ismore }) {
    this.goodsId = id;
    this.cate_id = cate_id;
    this.isFromMore = !!ismore;
  },
  onShow() {
    this.handleGetGoodsDetail();
  },
  methods: {
    handleSwiperChange({ target: { current } }) {
      this.current = current;
    },
    async handleGetGoodsDetail() {
      const [err, { data }] = await this.$captureCatch(
        goodsDetail({
          id: this.goodsId,
          cate_id: this.cate_id
        })
      );
      this.isLoading = false;
      /**进来时商品下架的异常处理 */
      if (err && err?.status_code === CATE_OFF_CODE) {
        /**如果是更多商品跳转过来的 应返回2级 */
        const delta = this.isFromMore ? 2 : 1;
        Taro.navigateBack({
          delta,
          success: () => {
            Taro.eventCenter.trigger("get-error", err?.message);
          }
        });
        return;
      }
      this.detailInfo = data;
      this.content = handleRichTextStyle(data.goods_content);
    },
    handleModalOperate({ target: { dataset } }) {
      const { key } = dataset;
      if (!key) return;
      let strategy = {};
      this.isShowModal = false;
      strategy["to-exchange"] = () => {
        Taro.navigateTo({
          url: "/pages/mine/petal/index"
        });
      };

      strategy[key] && strategy[key]();
    },
    /**立即兑换 */
    async handleExchangeGoods() {
      /**
       * 1. 公益商品直接兑换成功！
       * 2. 虚拟商品跳转兑换成功页！
       * 3. 实体商品跳转选择校区或者编辑地址页面...
       */

      try {
        if (this.isLoading) return;
        this.isLoading = true;
        const { data } = await goodsExchange({ id: this.goodsId });
        setTimeout(() => {
          this.isLoading = false;
        }, 500);
        const { exchange_type } = data;
        /**公益 */
        if (exchange_type === Public_Spirited_Type) {
          this.$message("兑换成功");
          this.handleGetGoodsDetail();
          return;
        }
        /**虚拟 */

        if (exchange_type === Fictitious_TYPE) {
          data.teacher = data?.teacher || {};
          const teacher = { ...data.teacher, copywriting: data.copywriting };
          Taro.navigateTo({
            url: `/pages/exchange-store/exchange-result/index?teacher=${JSON.stringify(
              teacher
            )}`
          });
          return;
        }
        if (exchange_type === Entity_TYPE) {
          const ismore = Number(this.isFromMore);
          Taro.navigateTo({
            url: `/pages/exchange-store/sure-exchange/index?data=${JSON.stringify(
              data
            )}&ismore=${ismore}`
          });
        }
      } catch ({ status_code, message }) {
        setTimeout(() => {
          this.isLoading = false;
        }, 500);
        /**栏目下架 */
        if (status_code === CATE_OFF_CODE) {
          /**如果是更多商品跳转过来的 应返回2级 */
          const delta = this.isFromMore ? 2 : 1;
          Taro.navigateBack({
            delta,
            success: () => {
              Taro.eventCenter.trigger("get-error", message);
            }
          });
          return;
        }
        /**花朵不足 */
        if (status_code == Not_Flower_Exchange_Code) {
          this.isShowModal = true;
          return;
        }
        /**库存不足 */
        if (status_code == Not_Enough_Stock_Code) {
          Taro.navigateTo({
            url: `/pages/exchange-store/exchange-result/index?notStock=${true}`
          });
          return;
        }
        this.$message(message);
      }
    }
  }
};
</script>

<style lang="scss">
@import "@/assets/scss/tools.scss";
.goods-detail {
  width: 100%;
  background-color: #fafafa;
  height: 100vh;
  display: flex;
  flex-direction: column;
  .scroll-wrap {
    flex: 1;
    overflow-x: hidden;
  }
  &-title {
    background-color: #ffffff;
  }
  &-head {
    margin-bottom: 32px;
    .swiper-wrap {
      width: 100%;
      height: 750px;
      position: relative;
      swiper,
      .head-img {
        width: 100%;
        height: 100%;
      }
      .extra-info {
        position: absolute;
        right: 24px;
        bottom: 24px;
        width: 102px;
        background: #303133;
        opacity: 0.55;
        border-radius: 100px;
        text-align: center;
        line-height: 52px;
        @include base-text(52px, 32px, #ffffff, 400);
      }
    }
    .head-main {
      padding: 32px 30px;
      box-sizing: border-box;
      height: 272px;
      background: #ffffff;
      &-title {
        @include base-text(auto, 40px, #000000);
        margin-bottom: 32px;
        display: -webkit-box;
        -webkit-box-orient: vertical;
        -webkit-line-clamp: 2;
        overflow: hidden;
        line-height: 48px;
        max-height: 92px;
      }
      &-extra {
        @include normal-flex(left);
        .exchange-num {
          text-align: right;
          flex: 1;
          @include base-text(40px, 28px, #909399, 400);
        }
        .over {
          width: 120px;
          background: #f3f3f3;
          border-radius: 200px;
          line-height: 48px;
          text-align: center;
          @include base-text(48px, 24px, #303133, 400);
        }
        .spand-flower {
          @include normal-flex(left);
          height: 80px;
          margin-right: 32px;
          text:last-child {
            @include base-text(44px, 32px, #303133, 400);
          }
          .flower-num {
            margin-right: 8px;
            @include base-text(80px, 56px, #ff8000);
          }
        }
        .surplus {
          box-sizing: border-box;
          padding: 0 24px;
          background: rgba(255, 128, 0, 0.08);
          border-radius: 200px;
          line-height: 48px;
          text-align: center;
          @include base-text(48px, 24px, #ff8000, 400);
        }
      }
    }
    .exchange-over {
      .flower-num {
        color: #909399 !important;
      }
    }
  }
  .goods-introduce {
    background: #ffffff;
    padding: 32px 30px 130px;
    box-sizing: border-box;
    &-title {
      @include base-text(50px, 36px, #303133);
      margin-bottom: 32px;
    }
    &-image image {
      width: 100%;
      vertical-align: top;
      height: 690px;
      margin-bottom: 24px;
    }
  }
  .finish-button-wrap {
    position: fixed;
    bottom: 16px;
    left: 50%;
    transform: translateX(-50%);
  }
}
</style>
